package com.lagou.springboot_homework.initializer;

import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: MySpringServletContainerInitializer
 * @Description: TODO
 * @Date: 2021/3/22 22:11
 * @Create by: shuiren
 */
public class MySpringServletContainerInitializer implements ServletContainerInitializer {

    @Override
    public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) {
        try {
            // 实例化所有 WebApplicationInitializer 的实现类
            List<WebApplicationInitializer> initializers = new ArrayList<WebApplicationInitializer>();
            if (webAppInitializerClasses != null){
                for (Class<?> initClass : webAppInitializerClasses) {
                    if (!initClass.isInterface() && !Modifier.isAbstract(initClass.getModifiers())){
                        initializers.add((WebApplicationInitializer) initClass.getConstructor().newInstance());
                    }
                }
            }
            // 调用其 onStartup 方法
            for (WebApplicationInitializer initializer : initializers) {
                initializer.onStartup(servletContext);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
